'use strict';

const Service = require('egg').Service;

class FileService extends Service {
	async isDirExist(file_id) {
		let f = await this.app.model.File.findOne({
			where: {
				id: file_id,
				user_id: this.ctx.authUser.id,
				isdir: 1
			}
		});
		if (!f) {
			return this.ctx.throw(404, '目录不存在!');
		}
	}
	async isExist(id) {
		let f = await this.app.model.File.findOne({
			where: {
				id: id,
				user_id: this.ctx.authUser.id
			}
		});
		if (!f) {
			return this.ctx.throw(404, '文件不存在!');
		}
		return f;
	}
	async formDir(params) {
		params.push();
		const result = [];
		for (const param of params) {
			if (param.file_id === 0) {
				// 顶层节点
				let parent = {
					id: param.id,
					name: param.name
				};
				parent.children = getChilds(param.id, params); // 获取子节点
				result.push(parent);
			}
		}

		function getChilds(id, array) {
			const childs = [];
			for (const arr of array) {
				if (arr.file_id === id) {
					// 循环获取子节点
					childs.push({
						id: arr.id,
						name: arr.name
					});
				}
			}
			// 获取子节点的子节点
			for (const child of childs) {
				const childsCopy = getChilds(child.id, array);
				if (childsCopy.length > 0) {
					child.children = childsCopy;
				}
			}
			return childs;
		}
		return result;
	}
}

module.exports = FileService;
